import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { Service } from 'app/server/server';
import { Http } from '@angular/http';
import { TreeService } from 'app/public/serve/tree/tree.service';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from 'primeng/primeng';
import { LoginService } from '../../../core/services/login.service';
import { Console } from '@angular/core/src/console';
import { HintsService } from '../../../public/serve/hints/hints.service';
declare var $: any;

@Component({
    selector: 'app-role-limit-tree',
    templateUrl: './role-limit-tree.component.html',
    styleUrls: ['./role-limit-tree.component.css']
})
export class RoleLimitTreeComponent implements OnInit {


    constructor(
        private server: Service,
        private http: Http,
        private httpc: HttpClient,
        private treeService: TreeService,
        private loginService: LoginService,
        private hintsService:HintsService
    ) { }
    treeStore = [] // 树结构备份
    treeData = [];
    selectedItems: any;
    roleId: string;
    formData: any = {};
    treeNodes = []; // 树结构数组
    createUserId: any;
    // @ViewChild("input") input:HTMLInputElement;
    query: any; //搜索的query
    ngOnInit() {
        // 树结构Url
        this.getTreeData().then((treeData) => {
            //console.log(this.treeData)
            this.treeData = treeData as any;
            this.treeStore = treeData as any;
        })
        this.rolebyeventEmit = this.server.rolebyeventEmit.subscribe((value: any) => {
            this.initModal();
            let urlRole = this.server.baseUrl+'user/functions/getRolePermissionList/' + value;
            this.roleId = value;
            this.http.get(urlRole).subscribe(res => {
                console.log(res)
                this.initFormData()
                let data = res.json().result as Array<{
                    functionId: string,
                    operation_id: string,
                    roleId: string
                }>;
                for (let item of data) {
                    this.formData[`${item.operation_id}:${item.functionId}`] = true
                }
            })
        })
        //用户id
        this.createUserId = this.server.getuser();
    }

    //取消订阅
    public rolebyeventEmit: any;
    ngOnDestroy() {
        if (this.rolebyeventEmit ) {
            this.rolebyeventEmit.unsubscribe();
        }
    }

    private initModal() {
        this.ztreeExpand(true)
        this.query = "";
        this.search();
        this.clearFilter();
    }
    initFormData() {
        for (let item in this.formData) {
            this.formData[item] = ""
        }
    }
    ztreeExpand(action?: boolean) {
        this.treeData.forEach(node => {
            this.expandRecursive(node, !!action);
        });
    }

    //更新权限
    upadteright() {
        let url = this.server.baseUrl+'admin/pusers/resetMenu';
        let data = { userId: this.createUserId }
        this.http.post(url, data).subscribe(res => {
            //console.log(res.json());
            this.server.right = this.loginService.processRights(res.json().result);
            this.server.setRight(this.server.right);
            this.server.righteventEmit.emit(true);
        })
    }

    submit() {
        let url = this.server.baseUrl+'user/functions/ModifierRolePermissionList';
        this.http.post(url, {
            roleId: this.roleId,
            selectedData: this.getSelectedData()
        }).subscribe(res => {
            this.hintsService.messages(res.json().message,res.json().result_code);
            if (res.json().result_code == "0000") {
                //console.log(res.json())
                this.upadteright();
                $("#roleLimitTree").modal("hide")
            }
        }, err => {
            console.error("请检查你的网络!")
        })
    }
    // 获取上传选中的权限id
    getSelectedData() {
        let result = []
        for (let item in this.formData) {
            if (this.formData[item]) {
                result = [...result, item]
            }
        }
        return JSON.stringify(result);
    }
    checkAll(action: boolean) {
        if (action) {
            for (let item in this.formData) {
                this.formData[item] = true
            }
        } else {
            for (let item in this.formData) {
                this.formData[item] = !this.formData[item]
            }
        }
    }
    clearAll() {
        for (let item in this.formData) {
            this.formData[item] = false
        }
    }
    nodeSelect($event) {
        //console.log($event)
    }
    search() {
        let query = $.trim(this.query);
        if (query) {
            this.ztreeExpand(false)
        }
        let reg = new RegExp(query, "g");
        this.filterNodes(query)
    }
    dblClick() {

    }
    private expandRecursive(node: any, isExpand: boolean, isExpandChldren: boolean = true) {
        node.expanded = isExpand;
        if (node.children && isExpandChldren) {
            node.children.forEach(childNode => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
    private getTreeData() {
        let idName = 'id';
        let parentId = '0';
        let parentIdName = 'pId';
        let labelName = 'name';
        let url = this.server.baseUrl+'user/functions/getPermissionList/';
        return this.http.get(url).toPromise().then(res => res.json()).then(res => {
            console.log(res)
            if (res.result_code != '0000') {
                throw new Error(res.message);
            } else {
                for (let item of res.result) {
                    this.initNode(item)
                }
                let result = this.toTree(res.result, parentId, idName, parentIdName, labelName);
                // 給每個 tree添加深度
                for (let item of result) {
                    this.fillTreeDeepin(item)
                }
                return result
            }
        }).catch((err: any) => {
            console.error('请检查您的网络！');
        });
    }
    // 冒泡排序 (给功能的操作权限排序 )
    bubbleSortByOperation(arr: Array<any>, key?: string) {
        key = key ? key : "id";
        for (let i = 0; i < arr.length - i; i++) {
            for (let j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j][key] < arr[j + 1][key]) {
                    [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
                }
            }
        }
        // // 把显示放在第一
        let showOperationKey
            = arr.findIndex(item => {
                if (item) {

                    return item.name == "显示"
                }
            })
        // arr.forEach((item, index) => {
        //     if (item.name == "显示") {
        //         showOperationKey = index
        //     }
        // })
        if (showOperationKey > 0) {
            // [arr[showOperationKey], arr[0]] = [arr[0], arr[showOperationKey]]
            let temp = arr[showOperationKey]
            arr[showOperationKey] = arr[0];
            arr[0] = temp;
        }
        return arr
    }
    private toTree(list: Array<any>, parentId = '0', idName, parentIdName, labelName) {
        let idKey = idName;
        let labelKey = labelName;
        let result = [];
        for (let item of list) {
            if (item[parentIdName] == parentId) {
                this.treeService.fillCSTreeNode(item, item[idKey], item[labelKey]);
                let children = this.toTree(list, item[idKey], idName, parentIdName, labelName)
                if (children && children.length > 0) {
                    item.children = children;
                    item.leaf = false;
                } else {
                    item.leaf = true;
                }
                result.push(item);
            }
        }
        return result;
    }
    // 单个节点初始化
    private initNode(node) {
        if (!node["permissionListes"]) {
            node["permissionListes"] = []
            return node
        }
        let permissionListes = (node["permissionListes"] as string).split(",");
        let result = []
        for (let item of permissionListes) {
            let operation = {
                id: item.split(":")[0],
                name: item.split(":")[1],
                formDataName: `${item.split(":")[0]}:${node.id}`
            }
            result = [...result, operation];
            this.formData[operation.formDataName] = ""
        }
        node["permissionListes"] = result;
        return node
    }
    // 给每课树增加深度
    private fillTreeDeepin(treeData: any, deep?: number) {
        deep = deep ? deep : 0;
        treeData.deep = deep;
        ++deep;
        if (treeData.children) {
            treeData.children.forEach(childNode => {
                this.fillTreeDeepin(childNode, deep)
            })
        }
    }
    // 把树结构推平成数组; 这个未完成
    private treeToleaf(treeData: Array<any>) {
        let tree = treeData
        let result = []
        for (let item of tree) {
            if (item.children) {
                this.treeToleaf(item.children)
                delete item.children
            }
            result = [...result, item]
        }
        return result
    }
    // 搜索事要隐藏的ids
    hiddenNodeIds: { [id: string]: boolean } | { [id: number]: boolean } = {};

    private _filterNode(ids, node, filterFn) {
        // if node passes function then it's visible
        let isVisible = filterFn(node);

        if (node.children) {
            // if one of node's children passes filter then this node is also visible
            node.children.forEach((child) => {
                if (this._filterNode(ids, child, filterFn)) {
                    isVisible = true;
                }
            });
        }

        // mark node as hidden
        if (!isVisible) {
            ids[node.id] = true;
        }
        // auto expand parents to make sure the filtered nodes are visible
        if (isVisible) {
            // node.ensureVisible();
            this.expandRecursive(node, true, false)
        }
        return isVisible;
    }
    private filterNodes(filter: string) {
        let filterFn;
        let reg = new RegExp(filter, "g");
        if (!filter) {
            return this.clearFilter();
        }

        // support function and string filter

        filterFn = (node) => reg.test(node.label);

        const ids = {};
        this.treeStore.forEach((node) => this._filterNode(ids, node, filterFn));
        this.hiddenNodeIds = ids;
    }
    private clearFilter() {
        this.hiddenNodeIds = {}
    }
    isEmpty(obj) {
        return JSON.stringify(obj) == "{}"
    }
    /**
     * 
     * @param  $event [boolean] checkbox的值
     * @param item 
     */
    clickCheckBox($event, item) {
        if (item.name == "显示") {
            // 获取该节点的id
            let nodeId = (item.formDataName as string).split(":")[1]
            // 获取该节点的功能id
            let nodeFucId = (item.formDataName as string).split(":")[0];
            let node = this.findInTree(this.treeData, nodeId, "id");
            let brother
            if (node.parent) {
                brother = node.parent.children
            }
            let findParent = (_node) => {
                this.formData[`${nodeFucId}:${_node.id}`] = true
                if (_node.parent) {
                    findParent(_node.parent)
                }
            }
            if ($event) {
                findParent(node)
            } else {
                this.parentNodeState(nodeFucId, node)
            }
            this.childrenNodeState(nodeFucId, node, $event)
        }

        //console.log(item)
    }
    findInTree(trees: Array<any>, id: string, idName: string): any {
        let result;
        for (let tree of trees) {
            if (tree[idName] === id) {
                result = tree;
                break;
            }
        }
        if (result) return result;
        for (let tree of trees) {
            if (tree.children) {
                result = this.findInTree(tree.children, id, idName);
                if (result) break;
            }
        }
        return result;
    }
    // 这个有问题
    findChildrenNodes(_node) {
        let result = [];
        let findMethod = (_node) => {
            if (_node.children) {
                result = [...result, ..._node.findChildrenNodes]
                for (let node of _node.children) {
                    findMethod(node)
                }
            }
        }
        findMethod(_node)
        return result
    }
    // 获取兄弟节点
    getNodeBother(node: TreeNode): Array<TreeNode> {
        if (node.parent) {
            return node.parent.children
        }
    }
    // 根据兄弟节点有没有勾上来绑定父节点的状态
    parentNodeState(nodeFucId: string, node: any) {
        if (!node.parent) {
            return
        }
        let botherNodes = this.getNodeBother(node)
        let parentNode = node.parent ? node.parent : null
        let isBotherNodesClick = false; // 同级有没有选中的
        for (let _node of botherNodes) {
            if (this.formData[`${nodeFucId}:${_node.data}`]) {
                if (_node.data == node.data) {
                    continue
                }
                isBotherNodesClick = true
                break;
            }
        }
        if (!isBotherNodesClick) {
            this.formData[`${nodeFucId}:${parentNode.data}`] = false
            if (parentNode && parentNode.parent) {
                this.parentNodeState(nodeFucId, parentNode)
            }
        }
    }
    // 当点击父级的显示CheckBox时，也让children节点也发生改变
    childrenNodeState(nodeFucId, node, $event: boolean) {
        if (node.children) {
            for (let _node of node.children) {
                this.formData[`${nodeFucId}:${_node.data}`] = $event
                if (_node && _node.children) {
                    this.childrenNodeState(nodeFucId, _node, $event)
                }
            }
        }
    }
    test() {
        this.formData["e742e5871ec4453d9e53ae5cd3d9108f:97b15e7ea6844c0f868c32e90be6f629"] =
            !this.formData["e742e5871ec4453d9e53ae5cd3d9108f:97b15e7ea6844c0f868c32e90be6f629"]
    }
}
